﻿using Autofac;
using System;
using System.Linq;
namespace Cyss.Core
{

    /// <summary>
    /// ioc 自动注册
    /// </summary>
    public partial class AutoFacModule : Autofac.Module
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        protected override void Load(ContainerBuilder builder)
        {
            AutofacManage.RegisterDependencies(builder);
            builder.RegisterBuildCallback(container => AutofacManage.container = container);
        }
    }

    /// <summary>
    /// 
    /// </summary>
    public class AutofacManage
    {
        /// <summary>
        /// 
        /// </summary>
        public static Autofac.ILifetimeScope container;

        /// <summary>
        ///  Register dependencies
        /// </summary>
        /// <param name="containerBuilder"></param>
        public static  void RegisterDependencies(ContainerBuilder containerBuilder)
        {
       
            //find dependency registrars provided by other assemblies
            var dependencyRegistrars = AppDomain.CurrentDomain.GetAssemblies().SelectMany(ass=> ass.GetTypes().Where(x => (x.GetInterfaces().Contains(typeof(IDependencyRegistrar)))));

            //create and sort instances of dependency registrars
            var instances = dependencyRegistrars
                .Select(dependencyRegistrar => (IDependencyRegistrar)Activator.CreateInstance(dependencyRegistrar));

            //register all provided dependencies
            foreach (var dependencyRegistrar in instances)
                dependencyRegistrar.Register(containerBuilder);
        }

    }


}
